package com.bbm.communitysystem.service.impl;

import com.bbm.communitysystem.domain.Router;
import com.bbm.communitysystem.domain.dto.role.RouterDto;
import com.bbm.communitysystem.mapper.RouterMapper;
import com.bbm.communitysystem.service.IRouterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bbm
 * @since 2025-02-13
 */
@Slf4j
@Service
public class RouterServiceImpl extends ServiceImpl<RouterMapper, Router> implements IRouterService {

    @Override
    public int addRouter(RouterDto router) {

        Router router1 = new Router();

        router1.setRouterName(router.getName());
        router1.setRouterUrl(router.getUrl());
        router1.setRouterPagePath(router.getPagePath());
        router1.setUpdateBy(router.getUpdateBy());
        router1.setStatus(0);
        router1.setUpdateTime(System.currentTimeMillis() + "");

        boolean save = save(router1);

        if (!save) {
            return 1;
        }

        log.info("添加路由：{}", router1);

        return 0;
    }

    @Override
    public int delRouter(Integer id) {
        log.info("删除路由：{}", id);
        return removeById(id) ? 0 : 1;
    }

    @Override
    public int putRouter(RouterDto router) {

        boolean update = lambdaUpdate()
                .set(!router.getName().isEmpty(), Router::getRouterName, router.getName())
                .set(!router.getPagePath().isEmpty(), Router::getRouterPagePath, router.getPagePath())
                .set(!router.getUrl().isEmpty(), Router::getRouterUrl, router.getUrl())
                .set(router.getStatus() != null, Router::getStatus, router.getStatus())

                .set(Router::getUpdateTime, System.currentTimeMillis() + "")
                .set(Router::getUpdateBy, router.getUpdateBy())
                .eq(Router::getId, router.getId())
                .update();

        if (!update) {
            return 1;
        }
        log.info("修改路由：{}", router);

        return 0;
    }

    @Override
    public RouterDto getRouter(Integer id) {
        Router byId = getById(id);

        if (byId == null) {
            return null;
        }

        RouterDto routerDto = new RouterDto();

        routerDto.setId(byId.getId());
        routerDto.setName(byId.getRouterName());
        routerDto.setPagePath(byId.getRouterPagePath());
        routerDto.setUrl(byId.getRouterUrl());
        routerDto.setStatus(byId.getStatus());
        routerDto.setUpdateBy(byId.getUpdateBy());

        return routerDto;
    }

    @Override
    public RouterDto[] getRouterList(Integer[] ids) {

        RouterDto[] routerDtos = new RouterDto[ids.length];

        for (int i = 0; i < ids.length; i++) {
            routerDtos[i] = getRouter(ids[i]);
        }
        return routerDtos;
    }
}
